<template>
  <div class="question-management-container">
    <div class="page-header">
      <h2>题目管理</h2>
      <div class="header-actions">
        <el-button 
          type="primary" 
          @click="createQuestion"
          :icon="Plus"
          round
        >
          创建题目
        </el-button>
        <el-button 
          type="success" 
          @click="importQuestions"
          :icon="Upload"
          round
        >
          批量导入
        </el-button>
      </div>
    </div>

    <el-card class="filter-card" shadow="hover">
      <div class="filter-container">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="竞赛名称">
            <el-input
              v-model="filterForm.contestTitle"
              placeholder="输入竞赛名称"
              clearable
              @input="handleSearch"
            />
          </el-form-item>
          <el-form-item label="题目类型">
            <el-select 
              v-model="filterForm.typeId" 
              placeholder="选择题目类型"
              clearable
              @change="fetchQuestionList"
            >
              <el-option 
                v-for="type in questionTypes" 
                :key="type.id" 
                :label="type.typeName" 
                :value="type.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="难度">
            <el-select 
              v-model="filterForm.difficulty" 
              placeholder="选择难度"
              clearable
              @change="fetchQuestionList"
            >
              <el-option :label="'简单'" :value="1" />
              <el-option :label="'中等'" :value="2" />
              <el-option :label="'困难'" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="filterForm.status" 
              placeholder="选择状态"
              clearable
              @change="fetchQuestionList"
            >
              <el-option :label="'待审核'" :value="0" />
              <el-option :label="'已通过'" :value="1" />
              <el-option :label="'已拒绝'" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="关键词">
            <el-input 
              v-model="filterForm.keyword" 
              placeholder="搜索题目内容"
              clearable
              @input="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchQuestionList">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="question-list-card" shadow="hover">
      <el-table
        v-loading="loading"
        :data="questions"
        style="width: 100%"
        border
        row-key="id"
      >
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column prop="content" label="题目内容" min-width="300">
          <template #default="scope">
            <div class="question-content">
              <el-tooltip 
                class="box-item" 
                effect="dark" 
                :content="scope.row.content" 
                placement="top-start"
                :hide-after="0"
              >
                <div>{{ formatContent(scope.row.content) }}</div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="contestTitle" label="所属竞赛" width="180" align="center">
          <template #default="scope">
            <el-tooltip
              effect="dark"
              :content="scope.row.contestTitle"
              placement="top"
              :hide-after="0"
              v-if="scope.row.contestTitle && scope.row.contestTitle.length > 15"
            >
              <span>{{ formatText(scope.row.contestTitle, 15) }}</span>
            </el-tooltip>
            <span v-else>{{ scope.row.contestTitle || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="typeName" label="题目类型" width="100" align="center">
          <template #default="scope">
            <el-tag 
              :type="getTypeTagType(scope.row.typeId)" 
              effect="plain"
            >
              {{ getQuestionTypeName(scope.row.typeId) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="100" align="center">
          <template #default="scope">
            <el-tag 
              :type="getDifficultyTagType(scope.row.difficulty)" 
              effect="light"
            >
              {{ getDifficultyText(scope.row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分值" width="80" align="center" />
        <el-table-column prop="timeLimit" label="时间限制" width="100" align="center">
          <template #default="scope">
            {{ scope.row.timeLimit }}秒
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag 
              :type="getStatusTagType(scope.row.status)" 
              effect="light"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button 
              type="primary" 
              link
              size="small"
              @click="viewQuestion(scope.row.id)"
            >
              查看
            </el-button>
            <el-button 
              type="success" 
              link
              size="small"
              @click="editQuestion(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              link
              size="small"
              @click="deleteQuestionConfirm(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          hide-on-single-page
        />
      </div>
    </el-card>

    <!-- 批量导入题目对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="批量导入题目"
      width="600px"
    >
      <el-form :model="importForm" label-width="100px">
        <el-form-item label="选择竞赛" required>
          <el-select 
            v-model="importForm.contestId" 
            placeholder="选择竞赛"
            style="width: 100%"
          >
            <el-option 
              v-for="contest in contestOptions" 
              :key="contest.id" 
              :label="contest.title" 
              :value="contest.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件上传" required>
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1"
            accept=".csv,.xlsx,.xls"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传Excel或CSV格式文件，<el-link type="primary" @click="downloadTemplate">下载模板</el-link>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitImport"
            :loading="importLoading"
          >
            开始导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Upload, 
  Search, 
  Refresh
} from '@element-plus/icons-vue'
import { 
  getQuestionList, 
  getQuestionTypes, 
  deleteQuestion,
  downloadQuestionTemplate,
  importQuestionsByExcel
} from '@/api/question'
import { getContestList } from '@/api/contest'

const router = useRouter()
const loading = ref(false)
const importLoading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 题目数据
const questions = ref([])
const questionTypes = ref([])
const contestOptions = ref([])

// 过滤表单
const filterForm = reactive({
  contestTitle: '',
  typeId: '',
  difficulty: '',
  status: '',
  keyword: ''
})

// 批量导入相关
const importDialogVisible = ref(false)
const importForm = reactive({
  contestId: '',
  file: null
})

// 获取题目列表
const fetchQuestionList = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      ...filterForm
    }

    const res = await getQuestionList(params)
    questions.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error('获取题目列表失败', error)
    ElMessage.error('获取题目列表失败')
  } finally {
    loading.value = false
  }
}

// 获取题目类型
const fetchQuestionTypes = async () => {
  try {
    const res = await getQuestionTypes()
    questionTypes.value = res.data
  } catch (error) {
    console.error('获取题目类型失败', error)
    ElMessage.error('获取题目类型失败')
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchQuestionList()
}

// 重置过滤条件
const resetFilter = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
  currentPage.value = 1
  fetchQuestionList()
}

// 处理页面大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchQuestionList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchQuestionList()
}

// 创建题目
const createQuestion = () => {
  router.push(`/contest/question/create/`)
}

// 编辑题目
const editQuestion = (id) => {
  router.push(`/contest/question/edit/${id}`)
}

// 查看题目
const viewQuestion = (id) => {
  router.push({
    path: `/contest/question/edit/${id}`,
    query: { readonly: 'true' }
  })
}

// 删除题目确认
const deleteQuestionConfirm = (id) => {
  ElMessageBox.confirm(
    '确定要删除此题目吗？删除后不可恢复。',
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteQuestion(id)
      ElMessage.success('删除题目成功')
      fetchQuestionList()
    } catch (error) {
      console.error('删除题目失败', error)
      ElMessage.error('删除题目失败')
    }
  }).catch(() => {})
}

// 批量导入题目
const importQuestions = () => {
  importDialogVisible.value = true
  fetchContestOptions() // 获取竞赛列表用于下拉框显示
}

// 获取竞赛列表
const fetchContestOptions = async () => {
  try {
    const res = await getContestList({
      current: 1,
      size: 100
    })
    contestOptions.value = res.data.records
  } catch (error) {
    console.error('获取竞赛列表失败', error)
    ElMessage.error('获取竞赛列表失败')
  }
}

// 文件变更
const handleFileChange = (file) => {
  importForm.file = file.raw
}

// 下载模板
const downloadTemplate = () => {
  try {
    // 直接通过API下载模板文件
    downloadQuestionTemplate().then(response => {
      // 创建Blob对象，直接使用response.data（二进制数据）
      const blob = new Blob([response.data], { 
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
      })
      
      // 获取文件名
      let fileName = 'question_import_template.xlsx'
      const contentDisposition = response.headers['content-disposition']
      if (contentDisposition) {
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
        const matches = filenameRegex.exec(contentDisposition)
        if (matches != null && matches[1]) {
          fileName = matches[1].replace(/['"]/g, '')
        }
      }
      
      // 创建下载链接并自动点击
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = fileName
      link.click()
      window.URL.revokeObjectURL(link.href)
    }).catch(error => {
      console.error('下载模板失败', error)
      ElMessage.error('下载模板失败')
    })
  } catch (error) {
    console.error('下载模板失败', error)
    ElMessage.error('下载模板失败')
  }
}

// 提交导入
const submitImport = async () => {
  if (!importForm.contestId) {
    ElMessage.warning('请选择竞赛')
    return
  }
  
  if (!importForm.file) {
    ElMessage.warning('请选择文件')
    return
  }
  
  importLoading.value = true
  try {
    // 创建FormData对象用于文件上传
    const formData = new FormData()
    formData.append('contestId', importForm.contestId)
    formData.append('file', importForm.file)
    
    // 调用文件上传接口
    const res = await importQuestionsByExcel(formData)
    
    if (res.code === 200) {
      ElMessage.success(`成功导入${res.data}道题目`)
      importDialogVisible.value = false
      fetchQuestionList()
    } else {
      ElMessage.error(res.message || '导入失败')
    }
  } catch (error) {
    console.error('导入题目失败', error)
    ElMessage.error('导入题目失败')
  } finally {
    importLoading.value = false
  }
}

// 格式化题目内容（截断长文本）
const formatContent = (content) => {
  if (!content) return ''
  return content.length > 100 ? content.substring(0, 100) + '...' : content
}

// 格式化文本（通用）
const formatText = (text, length) => {
  if (!text) return ''
  return text.length > length ? text.substring(0, length) + '...' : text
}

// 获取题目类型名称
const getQuestionTypeName = (typeId) => {
  const type = questionTypes.value.find(t => t.id === typeId)
  return type ? type.typeName : '未知类型'
}

// 获取类型标签类型
const getTypeTagType = (typeId) => {
  const types = {
    1: 'primary',   // 单选题
    2: 'success',   // 多选题
    3: 'warning',   // 判断题
    4: 'danger',    // 填空题
    5: 'info'       // 简答题
  }
  return types[typeId] || 'info'
}

// 获取难度文本
const getDifficultyText = (difficulty) => {
  const texts = {
    1: '简单',
    2: '中等',
    3: '困难'
  }
  return texts[difficulty] || '未知'
}

// 获取难度标签类型
const getDifficultyTagType = (difficulty) => {
  const types = {
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return types[difficulty] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝'
  }
  return texts[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return types[status] || 'info'
}

onMounted(() => {
  fetchQuestionTypes()
  fetchQuestionList()
})
</script>

<style lang="scss" scoped>
.question-management-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
      font-size: 24px;
      font-weight: 600;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .filter-card {
    margin-bottom: 20px;
    
    .filter-container {
      .filter-form {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }
  
  .question-list-card {
    .question-content {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 400px;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 